package io.github.hadyang.leetcode;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author haoyang.shi
 * @date 2020-02-02
 */
public class ListCodeC {
  private static final Pattern ARRAY_INT_PATTERN =
      Pattern.compile("\\[(\\s*-?\\d+,?)+]", Pattern.MULTILINE);

  private static final Pattern ARRAY_STR_PATTERN =
      Pattern.compile("\\[(\\s*\"\\w+\",?)+]", Pattern.MULTILINE);

  /**
   * @param data [1,2,3]
   * @return
   */
  public static List<Integer> deserializeInt(String data) {
    String numsStr = data.replaceAll("\\[", "").replaceAll("]", "");
    List<String> splited = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(numsStr);

    List<Integer> res = Lists.newArrayListWithExpectedSize(splited.size());
    for (String numStr : splited) {
      res.add(Integer.parseInt(numStr, 10));
    }

    return res;
  }

  /**
   * @param data [1,2,3]
   * @return
   */
  public static List<String> deserializeString(String data) {
    String numsStr = data.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "");
    List<String> splited = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(numsStr);

    List<String> res = Lists.newArrayListWithExpectedSize(splited.size());
    for (String str : splited) {
      res.add(str);
    }

    return res;
  }

  /**
   * @param data [1,2,3]
   * @return
   */
  public static List<List<String>> deserializeStringGraph(String data) {
    List<List<String>> resList = Lists.newArrayList();
    Matcher matcher = ARRAY_STR_PATTERN.matcher(data);
    while (matcher.find()) {
      resList.add(deserializeString(matcher.group(0)));
    }

    return resList;
  }

  /**
   * @param data [1,2,3]
   * @return
   */
  public static List<List<Integer>> deserializeIntGraph(String data) {
    List<List<Integer>> resList = Lists.newArrayList();

    Matcher matcher = ARRAY_INT_PATTERN.matcher(data);
    while (matcher.find()) {
      resList.add(deserializeInt(matcher.group(0)));
    }

    return resList;
  }
}
